#pragma once
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>
#include <unordered_map>
#include "log.hpp"

enum
{
    SOCK_ERR = 1
};

uint16_t defaultport = 8000;
std::string defaultip = "0.0.0.0";
using func_t = std::function<std::string(const std::string &)>; //定义函数类型
//typedef std::function<std::string(const std::string &)> func_t

Log log;
class server
{ 
public:
    server(const std::string ip = defaultip, const uint16_t port = defaultport)
    {
        _ip = ip;
        _port = port;
        _sockfd = 0;
    }

    void init()
    {
        //1.创建套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            log.logmessage(fatal, "socket create error:%d", _sockfd);
            exit(SOCK_ERR);
        }

        log.logmessage(info, "socket create success:%d", _sockfd);

        //绑定
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_addr.s_addr = inet_addr(_ip.c_str());
        local.sin_port = htons(_port);
        //local.sin_addr.s_addr = INADDR_ANY;

        int ret = bind(_sockfd, (const sockaddr*)&local, sizeof(local));
        if (ret < 0)
        {
            log.logmessage(fatal, "bind error:%s", strerror(errno));
        }
        log.logmessage(info, "bind success:%d", ret);

    }

    void checkuser(const struct sockaddr_in& sock, const string ip, const uint16_t port)
    {
        auto it = _online.find(ip);
        if (it == _online.end())
        {
            _online.insert({ip, sock});
            cout << "[" << ip << ":" << port << "] add new user" << endl;
        }
    }

    void broadcast(const string& message, string ip, uint16_t port)
    {
        for (const auto user : _online)
        {
            socklen_t len = sizeof(user.second);
            sendto(_sockfd, message.c_str(), message.size(), 0, (struct sockaddr*)(&user.second), len);
        }
    }

    void run(func_t func)
    {
        _isrunning = true;
        char buff[1024];
        while (_isrunning)
        {
            sockaddr_in client;
            socklen_t len = sizeof(client);
            ssize_t n = recvfrom(_sockfd, buff, sizeof(buff) - 1, 0, (sockaddr*)&client, &len);
            if (n < 0)
            {
                //log.logmessage(warning, "recv error:%s", strerror(errno));
                continue;
            }

            buff[n] = 0;
            //获取端口号和ip
            string ip = inet_ntoa(client.sin_addr);
            // 网络字节序转主机
            uint16_t port = ntohs(client.sin_port);

            checkuser(client, ip, port);
            std::string echo_string = "[" + ip + ":" + to_string(port) + "]: " + buff;
            broadcast(echo_string, ip, port);
            // std::cout << echo_string << endl;
            //  echo_string = func(echo_string);
            //sendto(_sockfd, echo_string.c_str(), echo_string.size(), 0, (const sockaddr *)&client, len);
        }
    }
 
    ~server()
    {
        if (_sockfd > 0)
            close(_sockfd);
    }

private:
    int _sockfd;      // 网路文件描述符
    uint16_t _port;   // 任意地址bind 0
    std::string _ip;  // 表明服务器进程的端口号
    bool _isrunning;
    //用ip检索
    unordered_map<string, struct sockaddr_in> _online;  //注册主机
};